extends Node2D

# 引用战斗管理器和UI管理器
var battle_manager
var ui_manager

# 战斗场景元素
var player_monster_container
var enemy_monster_container
var battle_ui_container
var animation_container

# 战斗状态
var is_battle_active = false
var is_player_turn = false
var selected_action = ""
var selected_skill_index = -1

# 初始化战斗场景
func _ready():
	print("战斗场景初始化")
	
	# 初始化容器
	player_monster_container = $PlayerMonsterContainer
	enemy_monster_container = $EnemyMonsterContainer
	battle_ui_container = $BattleUIContainer
	battle_ui_container.z_index = 10
	animation_container = $AnimationContainer
	
	# 创建战斗管理器
	battle_manager = BattleManager.new()
	add_child(battle_manager)
	
	# 创建UI管理器
	ui_manager = UIManager.new()
	ui_manager.initialize()
	add_child(ui_manager)
	
	# 注册UI元素
	ui_manager.register_ui_element("battle_ui", battle_ui_container)
	ui_manager.register_ui_element("player_status", $BattleUIContainer/BattleUI/PlayerMonsterStatus)
	ui_manager.register_ui_element("enemy_status", $BattleUIContainer/BattleUI/EnemyMonsterStatus)
	
	# 连接信号
	battle_manager.battle_ended.connect(Callable(self, "_on_battle_ended"))
	battle_manager.turn_changed.connect(Callable(self, "_on_turn_changed"))
	battle_manager.monster_action.connect(Callable(self, "_on_monster_action"))
	battle_manager.monster_defeated.connect(Callable(self, "_on_monster_defeated"))
	
	# 设置UI状态
	ui_manager.change_state(ui_manager.UIState.BATTLE)

# 开始战斗
func start_battle(player_team, enemy_team):
	print("开始战斗")
	is_battle_active = true
	
	# 初始化战斗管理器
	battle_manager.initialize_battle(player_team, enemy_team)
	
	# 显示幻兽
	_display_monsters(player_team, enemy_team)
	
	# 开始战斗
	battle_manager.start_battle()
	
	return true

# 显示幻兽
func _display_monsters(player_team, enemy_team):
	# 清空容器
	for child in player_monster_container.get_children():
		player_monster_container.remove_child(child)
		child.queue_free()
	
	for child in enemy_monster_container.get_children():
		enemy_monster_container.remove_child(child)
		child.queue_free()
	
	# 显示玩家幻兽
	for i in range(player_team.size()):
		var monster = player_team[i]
		var monster_sprite = Sprite2D.new()
		
		# 设置精灵图
		# 注意: 在实际游戏中，这里会加载实际的精灵图
		monster_sprite.texture = load("res://icon.png")  # 临时使用默认图标
		monster_sprite.position = Vector2(100, 300 + i * 100)
		monster_sprite.scale = Vector2(2, 2)
		monster_sprite.name = "PlayerMonster" + str(i)
		
		player_monster_container.add_child(monster_sprite)
	
	# 显示敌方幻兽
	for i in range(enemy_team.size()):
		var monster = enemy_team[i]
		var monster_sprite = Sprite2D.new()
		
		# 设置精灵图
		# 注意: 在实际游戏中，这里会加载实际的精灵图
		monster_sprite.texture = load("res://icon.png")  # 临时使用默认图标
		monster_sprite.position = Vector2(700, 300 + i * 100)
		monster_sprite.scale = Vector2(2, 2)
		monster_sprite.name = "EnemyMonster" + str(i)
		
		enemy_monster_container.add_child(monster_sprite)

# 更新战斗UI
func _update_battle_ui():
	if not is_battle_active:
		return
	
	# 获取当前战斗状态
	var battle_state = battle_manager.get_battle_state()
	var battle_state_name = battle_manager.get_battle_state_name()
	
	# 更新UI
	var battle_ui = battle_ui_container.get_node("BattleUI")
	if battle_ui:
		# 更新状态文本
		var state_label = battle_ui.get_node("StateLabel")
		if state_label:
			state_label.text = "战斗状态: " + battle_state_name
		
		# 更新回合文本
		var turn_label = battle_ui.get_node("TurnLabel")
		if turn_label:
			turn_label.text = "回合: " + str(battle_manager.turn_count)
		
		# 更新行动按钮
		var action_buttons = battle_ui.get_node("ActionButtons")
		if action_buttons:
			action_buttons.visible = is_player_turn

# 处理玩家行动
func _on_action_button_pressed(action):
	if not is_battle_active or not is_player_turn:
		return
	
	selected_action = action
	
	match action:
		"attack":
			# 直接执行攻击
			battle_manager.player_action("attack")
		
		"skill":
			# 显示技能选择界面
			var skill_buttons = battle_ui_container.get_node("BattleUI/SkillButtons")
			if skill_buttons:
				skill_buttons.visible = true
		
		"item":
			# 显示道具选择界面
			var item_buttons = battle_ui_container.get_node("BattleUI/ItemButtons")
			if item_buttons:
				item_buttons.visible = true
		
		"run":
			# 尝试逃跑
			battle_manager.player_action("run")

# 处理技能选择
func _on_skill_button_pressed(skill_index):
	if not is_battle_active or not is_player_turn or selected_action != "skill":
		return
	
	selected_skill_index = skill_index
	
	# 执行技能
	battle_manager.player_action("skill", skill_index)
	
	# 隐藏技能选择界面
	var skill_buttons = battle_ui_container.get_node("BattleUI/SkillButtons")
	if skill_buttons:
		skill_buttons.visible = false

# 处理道具选择
func _on_item_button_pressed(item_index):
	if not is_battle_active or not is_player_turn or selected_action != "item":
		return
	
	# 执行道具使用
	battle_manager.player_action("item", -1, item_index)
	
	# 隐藏道具选择界面
	var item_buttons = battle_ui_container.get_node("BattleUI/ItemButtons")
	if item_buttons:
		item_buttons.visible = false

# 战斗结束回调
func _on_battle_ended(result):
	is_battle_active = false
	
	# 显示结果
	var result_label = battle_ui_container.get_node("BattleUI/ResultLabel")
	if result_label:
		match result:
			battle_manager.BattleState.VICTORY:
				result_label.text = "战斗胜利!"
			battle_manager.BattleState.DEFEAT:
				result_label.text = "战斗失败!"
			_:
				result_label.text = "战斗结束"
		
		result_label.visible = true
	
	# 显示继续按钮
	var continue_button = battle_ui_container.get_node("BattleUI/ContinueButton")
	if continue_button:
		continue_button.visible = true

# 回合变化回调
func _on_turn_changed(turn_type, monster):
	is_player_turn = (turn_type == "player")
	
	# 更新UI
	_update_battle_ui()
	
	# 如果是玩家回合，显示行动按钮
	var action_buttons = battle_ui_container.get_node("BattleUI/ActionButtons")
	if action_buttons:
		action_buttons.visible = is_player_turn
	
	# 如果是敌方回合，隐藏所有选择界面
	if not is_player_turn:
		var skill_buttons = battle_ui_container.get_node("BattleUI/SkillButtons")
		if skill_buttons:
			skill_buttons.visible = false
		
		var item_buttons = battle_ui_container.get_node("BattleUI/ItemButtons")
		if item_buttons:
			item_buttons.visible = false

# 幻兽行动回调
func _on_monster_action(monster, target, action_result):
	# 播放攻击动画
	_play_attack_animation(monster, target, action_result)

# 幻兽被击败回调
func _on_monster_defeated(monster):
	# 播放击败动画
	_play_defeat_animation(monster)

# 播放攻击动画
func _play_attack_animation(attacker, target, action_result):
	# 获取攻击者和目标的精灵图
	var attacker_sprite
	var target_sprite
	
	if attacker in battle_manager.player_monsters:
		var index = battle_manager.player_monsters.find(attacker)
		attacker_sprite = player_monster_container.get_node("PlayerMonster" + str(index))
	else:
		var index = battle_manager.enemy_monsters.find(attacker)
		attacker_sprite = enemy_monster_container.get_node("EnemyMonster" + str(index))
	
	if target in battle_manager.player_monsters:
		var index = battle_manager.player_monsters.find(target)
		target_sprite = player_monster_container.get_node("PlayerMonster" + str(index))
	else:
		var index = battle_manager.enemy_monsters.find(target)
		target_sprite = enemy_monster_container.get_node("EnemyMonster" + str(index))
	
	if attacker_sprite and target_sprite:
		# 创建动画
		var animation = Animation.new()
		var animation_player = AnimationPlayer.new()
		animation_container.add_child(animation_player)
		
		# 设置动画轨道
		var track_index = animation.add_track(Animation.TYPE_VALUE)
		animation.track_set_path(track_index, str(attacker_sprite.get_path()) + ":position")
		
		# 保存原始位置
		var original_position = attacker_sprite.position
		var target_position = target_sprite.position
		
		# 设置关键帧
		animation.track_insert_key(track_index, 0.0, original_position)
		animation.track_insert_key(track_index, 0.2, original_position + (target_position - original_position) * 0.5)
		animation.track_insert_key(track_index, 0.4, original_position)
		
		# 设置动画长度
		animation.length = 0.5
		
		# 播放动画
		var attack_anim_lib = AnimationLibrary.new()
		attack_anim_lib.add_animation("attack", animation)
		animation_player.add_animation_library("attack", attack_anim_lib)
		animation_player.play("attack")
		
		# 创建伤害标签
		var damage_label = Label.new()
		damage_label.text = str(action_result.damage)
		damage_label.position = target_sprite.position + Vector2(0, -50)
		animation_container.add_child(damage_label)
		
		# 设置伤害标签动画
		var label_animation = Animation.new()
		var label_track_index = label_animation.add_track(Animation.TYPE_VALUE)
		label_animation.track_set_path(label_track_index, str(damage_label.get_path()) + ":rect_position")
		
		label_animation.track_insert_key(label_track_index, 0.0, damage_label.position)
		label_animation.track_insert_key(label_track_index, 1.0, damage_label.position + Vector2(0, -50))
		
		var label_alpha_track = label_animation.add_track(Animation.TYPE_VALUE)
		label_animation.track_set_path(label_alpha_track, str(damage_label.get_path()) + ":modulate:a")
		
		label_animation.track_insert_key(label_alpha_track, 0.0, 1.0)
		label_animation.track_insert_key(label_alpha_track, 1.0, 0.0)
		
		label_animation.length = 1.0
		
		var label_player = AnimationPlayer.new()
		animation_container.add_child(label_player)
		var label_lib = AnimationLibrary.new()
		label_lib.add_animation("fade", label_animation)
		label_player.add_animation_library("label_anim", label_lib)
		label_player.play("fade")
		
		# 设置动画完成后的清理
		await label_player.animation_finished
		damage_label.queue_free()
		label_player.queue_free()
		animation_player.queue_free()

# 播放击败动画
func _play_defeat_animation(monster):
	var monster_sprite
	
	if monster in battle_manager.player_monsters:
		var index = battle_manager.player_monsters.find(monster)
		monster_sprite = player_monster_container.get_node("PlayerMonster" + str(index))
	else:
		var index = battle_manager.enemy_monsters.find(monster)
		monster_sprite = enemy_monster_container.get_node("EnemyMonster" + str(index))
	
	if monster_sprite:
		# 创建动画
		var animation = Animation.new()
		var animation_player = AnimationPlayer.new()
		animation_container.add_child(animation_player)
		
		# 设置动画轨道
		var alpha_track = animation.add_track(Animation.TYPE_VALUE)
		animation.track_set_path(alpha_track, str(monster_sprite.get_path()) + ":modulate:a")
		
		# 设置关键帧
		animation.track_insert_key(alpha_track, 0.0, 1.0)
		animation.track_insert_key(alpha_track, 1.0, 0.0)
		
		# 设置动画长度
		animation.length = 1.0
		
		# 播放动画
		var defeat_anim_lib = AnimationLibrary.new()
		defeat_anim_lib.add_animation("defeat", animation)
		animation_player.add_animation_library("defeat", defeat_anim_lib)
		animation_player.play("defeat")
		
		# 设置动画完成后的清理
		await animation_player.animation_finished
		animation_player.queue_free()

# 继续按钮回调
func _on_continue_button_pressed():
	# 退出战斗场景
	queue_free()
